package lib

import (
	"log"

	"github.com/streadway/amqp"
)

var mqconn *amqp.Connection
var mqurl string
var mqchannel *amqp.Channel

func InitMQ(mqurlP string) {
	mqurl = mqurlP
	connMq()

	var err error
	mqchannel, err = mqconn.Channel()
	if err != nil {
		log.Print("get channel faild", err)
		connMq()
		mqchannel, _ = mqconn.Channel()
	}
}

func connMq() {
	if mqconn == nil || mqconn.IsClosed() {
		var err error
		mqconn, err = amqp.Dial(mqurl)
		if err != nil {
			log.Print("连接到RabbitMQ失败", err)
		}
	}
}

func GetMqChannel() *amqp.Channel {
	return mqchannel
}

func CallbackSync(replayto, correlationId, body string) {
	ch := GetMqChannel()
	err := ch.Publish(
		"",       //exchange
		replayto, //routing key
		false,    //mandatory
		false,    //immediate
		amqp.Publishing{
			ContentType:   "text/plain",
			CorrelationId: correlationId,
			Body:          []byte(body),
		})
	if err != nil {
		log.Print("同步消息失败")
	} else {
		log.Print("同步消息成功! ")
	}
}

func CreateMqConsume(exchangeName, exchangeType, queueName, routingKey string) <-chan ReceivedMsg {
	ch := GetMqChannel()
	ch.ExchangeDeclare(exchangeName, exchangeType,
		true,  // durable
		false, //autoDelete
		false, //internal
		false, //noWait
		nil)
	q, _ := ch.QueueDeclare(
		queueName, // name
		true,      // durable
		false,     // delete when unused
		false,     // exclusive
		false,     // no-wait
		nil,       // arguments
	)
	ch.QueueBind(queueName, routingKey, exchangeName, false, nil)

	_ = ch.Qos(
		1,     // prefetch count
		0,     // prefetch size
		false, //global
	)

	msgs, _ := ch.Consume(
		q.Name, // queue
		"",     // consumer
		false,  // auto-ack
		false,  // exclusive
		false,  // no-local
		false,  // no-wait
		nil,    // args
	)
	chan1 := make(chan ReceivedMsg)
	go func() {
		for d := range msgs {
			mb := Str2mb(string(d.Body))
			rm := new(ReceivedMsg)
			rm.MB = mb
			rm.ReplyTo = d.ReplyTo
			rm.CorrelationId = d.CorrelationId
			chan1 <- *rm
			d.Ack(false)
		}
	}()

	return chan1
}

type ReceivedMsg struct {
	MB            MessageBody
	ReplyTo       string
	CorrelationId string
}
